package com.zjw.algorithm;


/**
 * 写一个函数来查找字符串数组中的最长公共前缀。
 * <p>
 * 如果不存在公共前缀，返回空字符串 ""。
 * <p>
 * <p>
 * <p>
 * 示例 1：
 * <p>
 * 输入：strs = ["flower","flow","flight"]
 * 输出："fl"
 * 示例 2：
 * <p>
 * 输入：strs = ["dog","racecar","car"]
 * 输出：""
 * 解释：输入不存在公共前缀。
 */
public class Solution11 {

    public static void main(String[] args) {
        System.out.println(new Solution11().longestCommonPrefix(new String[]{"flower", "flow", "flight"}));
        System.out.println(new Solution11().longestCommonPrefix(new String[]{"dog","racecar","car"}));
    }

    public String longestCommonPrefix(String[] strs) {
        if (strs == null || strs.length == 0) {
            return "";
        }

        int p = 0;
        while (true) {
            for (String str : strs) {
                String target = strs[0];
                if (target.length() <= p) {
                    return target.substring(0, p);
                }

                if (str.length() <= p) {
                    return target.substring(0, p);
                }

                if (str.charAt(p) != target.charAt(p)) {
                    return target.substring(0, p);
                }
            }
            p++;
        }
    }
}
